package com.cml.rpc.server;


import com.cml.rpc.register.ServiceRegister;
import com.cml.rpc.register.ZkServiceRegister;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * 自动
 * @author cml
 * @create 2021/7/21 10:09
 */
public class ServiceProvider {
    private ServiceRegister serviceRegister;
    private Map<String,Object> serverProvider;
    private String host;
    private int port;

    public Map<String, Object> getServerProvider() {
        return serverProvider;
    }

    public ServiceProvider(String host, int port) {
        this.host = host;
        this.port = port;
        this.serverProvider = new HashMap<>();
        this.serviceRegister = new ZkServiceRegister();
    }

    public void put(Object service) {
        String serviceName = service.getClass().getName();
        Class<?>[] interfaces = service.getClass().getInterfaces();

        for (Class clazz : interfaces) {
            serverProvider.put(clazz.getName(), service);
            // 在服务注册中心注册服务
            serviceRegister.register(clazz.getName(), new InetSocketAddress(host, port));
        }
    }

    public Object get(String interfaceName) {
        Object server = serverProvider.get(interfaceName);
        return server;
    }
}
